package com.whcoding.test.common.http;

import com.alibaba.fastjson.JSONObject;
import kong.unirest.Unirest;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class BaseHttpUtil {
    @Autowired
    RestTemplate restTemplate;


    /**
     * 方法一：
     * JDK 自带的 URLConnection
     *
     * @param url
     * @param body
     * @return
     */
    public byte[] getWechatQrcodeByHttpURL(String url, Map<String, Object> body) {
        HttpURLConnection httpURLConnection = null;
        try {
            httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
            httpURLConnection.setRequestMethod("POST");
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            printWriter.write(JSONObject.toJSONString(body));
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            try (InputStream inputStream = httpURLConnection.getInputStream();
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                return out.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return null;
    }


    /**
     * 方法二:
     * Apache的HttpClient方式
     * Maven 依赖
     *  <dependency>
     *     <groupId>org.apache.httpcomponents</groupId>
     *     <artifactId>httpclient</artifactId>
     *     <version>4.5.12</version>
     * </dependency>
     * @param url
     * @param body
     * @return
     */
    public byte[] getWechatQrcodeByHttpClient(String url, Map<String, Object> body) {
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        try {
            StringEntity entity = new StringEntity(JSONObject.toJSONString(body));
            entity.setContentType("image/png");
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            try (InputStream inputStream = response.getEntity().getContent();
                 ByteArrayOutputStream out = new ByteArrayOutputStream()) {
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = inputStream.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                }
                return out.toByteArray();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 方法三：
     * okhttp3方式
     * Maven依赖
     * <dependency>
     *     <groupId>com.squareup.okhttp3</groupId>
     *     <artifactId>okhttp</artifactId>
     *     <version>3.14.2</version>
     * </dependency>
     * @param url
     * @param body
     * @return
     */
    public byte[] getWechatQrcodeByOkhttp3(String url, Map<String, Object> body) {
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
        RequestBody requestBody = RequestBody.create(mediaType, JSONObject.toJSONString(body));
        Request request = new Request.Builder().url(url).method("POST", requestBody).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().bytes();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 方法四：Unirest方式
     * Maven依赖：
     *<dependency>
     *     <groupId>com.konghq</groupId>
     *     <artifactId>unirest-java</artifactId>
     *     <version>3.11.11</version>
     * </dependency>
     * @param url
     * @param body
     * @return
     */
    public byte[] getWechatQrcodeByUnirest(String url, Map<String, Object> body) {
        return Unirest.post(url).body(JSONObject.toJSONString(body)).asBytes().getBody();
    }


    /**
     * 方法五：
     * RestTemplate方式
     * @param url
     * @param body
     * @return
     */
    public byte[] getWechatQrcodeByRestTemplate(String url, Map<String, Object> body) {
        return restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(body, null), byte[].class).getBody();
    }
}
